<script setup lang="ts">
import { add, update } from '@/api/system/role'
import type { FormRules } from 'element-plus'
import { notify } from '@/utils/element'

/**
 * 表单规则
 */
const rules = reactive<FormRules>({
  roleName: [{ required: true, message: '必填项！', trigger: 'blur' }],
  status: [{ required: true, message: '必填项！', trigger: 'blur' }],
})

// 定义状态
const state = reactive({
  visible: false,
  loading: false,
  title: '新增',
  type: 'add' as FormType,
  formData: {} as SysRoleType,
});

const { visible, loading, title, formData } = { ...toRefs(state) };

// 导出给父组件调用
defineExpose({
  open
});

/**
 * 打开窗口
 */
const initData = { status: true }
function open(type: FormType, title: string, data = {} as any) {
  state.type = type;
  state.title = title;
  // 合并数据并深度拷贝对象
  state.formData = JSON.parse(JSON.stringify({ ...initData, ...data }));
  state.visible = true;
}

// 关闭窗口
const formRef = ref()
function close() {
  if (state.loading) return;
  //清空表单，清除校验提示
  formRef.value?.resetFields();
  state.visible = false;
}

// 提交表单
function submitForm() {
  formRef.value?.validate((valid: any) => {
    if (!valid) return;
    submitData();
  });
}

// 提交数据
const emit = defineEmits(['refresh']);
async function submitData() {
  try {
    state.loading = true;
    let res;
    if (state.type === 'edit') {
      // 修改
      res = await update(state.formData);
    } else {
      // 新增
      res = await add(state.formData);
    }
    state.loading = false;// 防止close关闭不了窗口
    if (res.status !== 200) return;
    notify('操作成功！', { type: 'success' });
    // 关闭窗口
    close();
    // 触发事件让父组件刷新列表
    emit('refresh');
  } catch (e) {
  } finally {
    state.loading = false;
  }
}
</script>

<template>
  <el-dialog :title="`${title}角色`" v-model="visible" draggable close="close">
    <el-scrollbar max-height="460px">
      <el-form v-loading="loading" ref="formRef" :rules="rules" :model="formData" :label-width="100">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-switch v-model="formData.status" inline-prompt active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="formData.remarks" type="textarea" :autosize="{ minRows: 5 }" placeholder="请输入备注信息"
            maxlength="500" clearable show-word-limit />
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="flex items-center justify-center">
        <el-button class="w-29" type="info" @click="close">取 消</el-button>
        <el-button class="w-29" type="primary" :loading="loading" @click="submitForm">
          {{ loading ? '正在提交 ...' : '提 交' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>